package com.space.mygql.stitching;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.space.mygql.stitching.namespace.NameSpaceService;
import com.space.mygql.stitching.utils.InetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.file.Paths;
import java.util.List;

/**
 * @author <a href="mailto:414563035@qq.com">Bedroom</a>
 * @date 2021/5/26 5:20 下午
 */
@SpringBootApplication
@RestController
public class StitchingApplication implements CommandLineRunner, ApplicationListener<WebServerInitializedEvent> {
    @NacosInjected(properties = @NacosProperties(namespace = "MYGQL"))
    private NamingService namingService;

    @Autowired
    NameSpaceService nameSpaceService;

    @Autowired
    InetUtil inetUtil;

    private int serverPort;

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(StitchingApplication.class, args);
    }

    @GetMapping("/hello")
    public Mono<String> hello() {
        try {
            List<Instance> instances = namingService.getAllInstances("mygql-example");
            for (Instance instance : instances) {
                String result = restTemplate.getForObject("http://" + instance.getIp() + ":" + instance.getPort() + "/hello", String.class);
                System.out.println(result);
            }
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return Mono.just("Hello World");
    }

    @PostMapping(value = "/mygql/v1/schema", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Mono<String> schema(@RequestPart("files") Flux<FilePart> filePartFlux) {
        return filePartFlux.flatMap(filePart -> { ;
//            filePart.content().subscribe(buffer -> {
//
//            });
            return filePart.transferTo(Paths.get("/Users/bedroom/project/java/space/mygql/schemas/" + filePart.filename()));
        })
        .then(Mono.just("OK"));
    }

    @Value("${spring.application.name}")
    String applicationName;

    @Override
    public void run(String... args) throws Exception {
        nameSpaceService.publishNameSpace("MYGQL", "graphql", "graphql");
        // NacosServiceRegistry
        namingService.registerInstance(applicationName, inetUtil.findFirstNonLoopbackAddress().getHostAddress(), this.serverPort);
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
        this.serverPort = webServerInitializedEvent.getWebServer().getPort();
    }
}
